<template>
  <div class="info">
    <a-spin :spinning="spinning">
      <!--表单区    -->
      <div class="form">
        <a-form :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }" layout="vertical">
          <a-row>
            <a-col :span="12">
              <a-form-item label="标识" v-bind="validateInfos.key">
                <a-input v-model:value="modelRef.key" disabled placeholder="请输入角色英文标识" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="名称" v-bind="validateInfos.name">
                <a-input v-model:value="modelRef.name" :disabled="isDetl" placeholder="请输入角色名称" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-item label="表达式">
                <div style="position: relative">
                  <div style="position: absolute; top: -30px; left: 55px">
                    <a-tooltip>
                      <template #title>例: 1.manager:*</template>
                      <question-circle-outlined />
                    </a-tooltip>
                  </div>
                </div>
                <a-input v-model:value="modelRef.action" :disabled="isDetl" placeholder="请输入角色英文标识" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="分组">
                <a-select
                  v-model:value="selection.value"
                  :options="selection.options"
                  :fieldNames="{label: 'name', value: 'key'}"
                  mode="multiple"
                  placeholder="请选择"
                  @change="selection.onchange"
                ></a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-item label="匹配资源">
                <a-cascader v-model:value="modelRef.resources"
                            :field-names="{ label: 'key', value: 'key', children: 'children' }"
                            :options="resource.options" placeholder="请选择" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-item label="备注">
                <a-textarea
                  v-model:value="modelRef.describe"
                  placeholder="备注"
                  :disabled="isDetl"
                  :auto-size="{ minRows: 2, maxRows: 2 }"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-spin>
    <!--页脚按钮    -->
    <div class="=foot">
      <a-space :size="8">
        <a-button type="primary" @click="onSubmit">保存</a-button>
        <a-button @click="onReset">重置</a-button>
      </a-space>
    </div>
  </div>
</template>

<script setup>
import { defineComponent, toRaw, ref, watch, defineEmits, toRefs, inject, reactive, nextTick } from 'vue'
import { QuestionCircleOutlined } from '@ant-design/icons-vue'
import { Form } from 'ant-design-vue'
import factory from "@/views/permission-manag/factory";

const { currentItemId } = inject('roleParams')

const useForm = Form.useForm
const modelRef = reactive({
  key: '',
  name: '',
  action: '',
  groupList: [],
  describe: '',
  resources: [],
})

//==重置==================================
const backupData = {}
const onReset = () => {
  for (let key in backupData) {
    modelRef[key] = JSON.parse( JSON.stringify(backupData[key]) )
  }
  selection.value = []
  for(let key in modelRef['groupList']){
    selection.value.push(key)
  }
}
//==回显数据=========================================
const spinning = ref(true)
const getPermisDetial = () => {
  factory.getPermisDetial({ key: currentItemId.value.key }).then(res => {
    spinning.value = false
    for(let key in res.data){
      modelRef[key] = res.data[key]
      backupData[key] = JSON.parse( JSON.stringify(res.data[key]) )
      if (key === 'action') {
        resource.getResourcesForExp(modelRef[key])
      }
    }
    selection.getPermisGroup()
  })
}
getPermisDetial()

//==表单验证,保存====================================================
const rulesRef = reactive({
  name: [
    {
      required: true,
      message: '请输入中文名称',
    },
  ],
  key: [
    {
      required: true,
      message: '请输入英文标识',
    },
  ],
  scope: [
    {
      required: true,
      message: '请选择所属应用',
    },
  ],
})
const { validate, validateInfos } = useForm(modelRef, rulesRef, {
  //表单验证的输出: 字段 值 提示
  onValidate: (...args) => {
    console.log('表单验证的输出: 字段 值 提示', ...args)
  },
})
const emit = defineEmits(['update-success'])
const onSubmit = () => {
  validate()
    .then(() => {
      //表单验证无误后执行
      modelRef.groupList = selection.value
      factory.updatePermis(modelRef).then(res => {
        emit('update-success','')
      })
    })
    .catch((err) => {
      console.log('error', err)
    })
}

//==资源=====================================
const resource = reactive({
  options: [],
  onchangeInput: (val) => {
    resource.getResourcesForExp(val.target.value)
  },
  getResourcesForExp: (action = '') => {
    factory.getResourcesForExp({action}).then(res => {
      resource.options = res.data
    })
  }
})

//==分组 选择器========================================
const selection = reactive({
  value: [],
  options: [],
  onchange: () => {
  },
  //获得权限分组
  getPermisGroup: (search = '') => {
    factory.getPermisGroup({ search }).then((res) => {
      res.data.forEach((item) => {
        selection.options.push(item)
      })
      for(let key in modelRef['groupList']){
        selection.value.push(key)
      }
    })
  }
})


</script>

